package genesis.familytree.server.modules.sys.web;

import genesis.familytree.server.common.JsonResult;
import genesis.familytree.server.common.security.SystemAuthorizingRealm;
import genesis.familytree.server.common.security.SystemAuthorizingRealm.Principal;
import genesis.familytree.server.common.security.UsernamePasswordToken;
import genesis.familytree.server.common.utils.CaptchaUtils;
import genesis.familytree.server.common.utils.StringUtils;
import genesis.familytree.server.common.web.BaseAdminController;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 */
@Controller
@RequestMapping("${familytree.admin-path}")
public class SysController extends BaseAdminController {

    @RequestMapping("/index")
    public Object index() {
        return "modules/sys/index";
    }


    @RequestMapping("/dashboard")
    public Object dashboard() {
        return "modules/sys/dashboard";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Object viewLogin() {
        return "modules/sys/login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        HttpSession session) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }

            if (StringUtils.isBlank(username)) {
                result.paramError("username", "请输入用户名");
            }
            if (StringUtils.isBlank(password)) {
                result.paramError("password", "请输入登录密码");
            }

            if (result.isError()) {
                return result;
            }

            Subject subject = Principal.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);

                Principal shiroPrincipal = (Principal) subject.getPrincipal();
                //this.secUserService.updateAfterLogin(shiroPrincipal.getId(), CommonUtils.getClientIP(request));

                result.success();
            } catch(UnknownAccountException // 账号不存在
                        | IncorrectCredentialsException //密码不匹配
                    e ) {
                token.clear();
                result.error("用户名或密码不正确");
            } catch(Exception re) {
                token.clear();
                logger.error(re.getMessage(), re);
                result.error();
            }
        } catch (Exception ex) {
            result.error();
            logger.error(ex.getMessage(), ex);
        }

        return result;
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Object logout() {
        Principal.getSubject().logout();
        return "redirect:" + adminPath + "/login";
    }
}
